home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 21 / AACD 21.iso / AACD / Utilities / Ghostscript / src / zfile.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-01-01  |  28.6 KB  |  1,003 lines

  1. /* Copyright (C) 1989, 2000 Aladdin Enterprises.  All rights reserved.
  2.   
  3.   This file is part of AFPL Ghostscript.
  4.   
  5.   AFPL Ghostscript is distributed with NO WARRANTY OF ANY KIND.  No author or
  6.   distributor accepts any responsibility for the consequences of using it, or
  7.   for whether it serves any particular purpose or works at all, unless he or
  8.   she says so in writing.  Refer to the Aladdin Free Public License (the
  9.   "License") for full details.
  10.   
  11.   Every copy of AFPL Ghostscript must include a copy of the License, normally
  12.   in a plain ASCII text file named PUBLIC.  The License grants you the right
  13.   to copy, modify and redistribute AFPL Ghostscript, but only under certain
  14.   conditions described in the License.  Among other things, the License
  15.   requires that the copyright notice and this notice be preserved on all
  16.   copies.
  17. */
  18.  
  19. /*$Id: zfile.c,v 1.5.2.1 2000/11/02 15:05:08 igorm Exp $ */
  20. /* Non-I/O file operators */
  21. #include "memory_.h"
  22. #include "string_.h"
  23. #include "ghost.h"
  24. #include "gscdefs.h"        /* for gx_io_device_table */
  25. #include "gp.h"
  26. #include "gsfname.h"
  27. #include "gsstruct.h"        /* for registering root */
  28. #include "gxalloc.h"        /* for streams */
  29. #include "oper.h"
  30. #include "estack.h"        /* for filenameforall, .execfile */
  31. #include "ialloc.h"
  32. #include "ilevel.h"        /* %names only work in Level 2 */
  33. #include "interp.h"        /* gs_errorinfo_put_string prototype */
  34. #include "isave.h"        /* for restore */
  35. #include "iutil.h"
  36. #include "stream.h"
  37. #include "strimpl.h"
  38. #include "sfilter.h"
  39. #include "gxiodev.h"        /* must come after stream.h */
  40.                 /* and before files.h */
  41. #include "files.h"
  42. #include "main.h"        /* for gs_lib_paths */
  43. #include "store.h"
  44.  
  45. /* Import the IODevice table. */
  46. extern_gx_io_device_table();
  47.  
  48. /* Import the dtype of the stdio IODevices. */
  49. extern const char iodev_dtype_stdio[];
  50.  
  51. /* Forward references: file name parsing. */
  52. private int parse_file_name(P2(const ref * op, gs_parsed_file_name_t * pfn));
  53. private int parse_real_file_name(P4(const ref * op,
  54.                     gs_parsed_file_name_t * pfn,
  55.                     gs_memory_t *mem, client_name_t cname));
  56.  
  57. /* Forward references: other. */
  58. private int zopen_file(P4(const gs_parsed_file_name_t *pfn,
  59.               const char *file_access, stream **ps,
  60.               gs_memory_t *mem));
  61. private iodev_proc_open_file(iodev_os_open_file);
  62. private int execfile_finish(P1(i_ctx_t *));
  63. private int execfile_cleanup(P1(i_ctx_t *));
  64.  
  65. /*
  66.  * Since there can be many file objects referring to the same file/stream,
  67.  * we can't simply free a stream when we close it.  On the other hand,
  68.  * we don't want freed streams to clutter up memory needlessly.
  69.  * Our solution is to retain the freed streams, and reuse them.
  70.  * To prevent an old file object from being able to access a reused stream,
  71.  * we keep a serial number in each stream, and check it against a serial
  72.  * number stored in the file object (as the "size"); when we close a file,
  73.  * we increment its serial number.  If the serial number ever overflows,
  74.  * we leave it at zero, and do not reuse the stream.
  75.  * (This will never happen.)
  76.  *
  77.  * Storage management for this scheme is a little tricky.  We maintain an
  78.  * invariant that says that a stream opened at a given save level always
  79.  * uses a stream structure allocated at that level.  By doing this, we don't
  80.  * need to keep track separately of streams open at a level vs. streams
  81.  * allocated at a level.  To make this interact properly with save and
  82.  * restore, we maintain a list of all streams allocated at this level, both
  83.  * open and closed.  We store this list in the allocator: this is a hack,
  84.  * but it simplifies bookkeeping (in particular, it guarantees the list is
  85.  * restored properly by a restore).
  86.  *
  87.  * We want to close streams freed by restore and by garbage collection.  We
  88.  * use the finalization procedure for this.  For restore, we don't have to
  89.  * do anything special to make this happen.  For garbage collection, we do
  90.  * something more drastic: we simply clear the list of known streams (at all
  91.  * save levels).  Any streams open at the time of garbage collection will no
  92.  * longer participate in the list of known streams, but this does no harm;
  93.  * it simply means that they won't get reused, and can only be reclaimed by
  94.  * a future garbage collection or restore.
  95.  */
  96.  
  97. /* 
  98.  * Define the default stream buffer sizes.  For file streams,
  99.  * this is arbitrary, since the C library or operating system
  100.  * does its own buffering in addition.
  101.  * However, the buffer size for eexec decoding is NOT arbitrary:
  102.  * it must be at most 512.
  103.  */
  104. #define DEFAULT_BUFFER_SIZE 512
  105. const uint file_default_buffer_size = DEFAULT_BUFFER_SIZE;
  106.  
  107. /* An invalid file object */
  108. private stream invalid_file_stream;
  109. stream *const invalid_file_entry = &invalid_file_stream;
  110.  
  111. /* Initialize the file table */
  112. private int
  113. zfile_init(i_ctx_t *i_ctx_p)
  114. {
  115.     /* Create and initialize an invalid (closed) stream. */
  116.     /* Initialize the stream for the sake of the GC, */
  117.     /* and so it can act as an empty input stream. */
  118.  
  119.     stream *const s = &invalid_file_stream;
  120.  
  121.     s_init(s, NULL);
  122.     sread_string(s, NULL, 0);
  123.     s->next = s->prev = 0;
  124.     s_init_no_id(s);
  125.     return 0;
  126. }
  127.  
  128. /* Make an invalid file object. */
  129. void
  130. make_invalid_file(ref * fp)
  131. {
  132.     make_file(fp, avm_invalid_file_entry, ~0, invalid_file_entry);
  133. }
  134.  
  135. /* <name_string> <access_string> file <file> */
  136. private int
  137. zfile(i_ctx_t *i_ctx_p)
  138. {
  139.     os_ptr op = osp;
  140.     char file_access[3];
  141.     gs_parsed_file_name_t pname;
  142.     const byte *astr;
  143.     int code;
  144.     stream *s;
  145.  
  146.     check_read_type(*op, t_string);
  147.     astr = op->value.const_bytes;
  148.     switch (r_size(op)) {
  149.     case 2:
  150.         if (astr[1] != '+')
  151.         return_error(e_invalidfileaccess);
  152.         file_access[1] = '+';
  153.         file_access[2] = 0;
  154.         break;
  155.     case 1:
  156.         file_access[1] = 0;
  157.         break;
  158.     default:
  159.         return_error(e_invalidfileaccess);
  160.     }
  161.     switch (astr[0]) {
  162.     case 'r':
  163.     case 'w':
  164.     case 'a':
  165.         break;
  166.     default:
  167.         return_error(e_invalidfileaccess);
  168.     }
  169.     file_access[0] = astr[0];
  170.     code = parse_file_name(op - 1, &pname);
  171.     if (code < 0)
  172.     return code;
  173.     /*
  174.      * HACK: temporarily patch the current context pointer into the
  175.      * state pointer for stdio-related devices.  See ziodev.c for
  176.      * more information.
  177.      */
  178.     if (pname.iodev && pname.iodev->dtype == iodev_dtype_stdio) {
  179.     if (pname.fname)
  180.         return_error(e_invalidfileaccess);
  181.     pname.iodev->state = i_ctx_p;
  182.     code = (*pname.iodev->procs.open_device)(pname.iodev,
  183.                          file_access, &s, imemory);
  184.     pname.iodev->state = NULL;
  185.     } else {
  186.     if (pname.iodev == NULL)
  187.         pname.iodev = iodev_default;
  188.     code = zopen_file(&pname, file_access, &s, imemory);
  189.     }
  190.     if (code < 0)
  191.     return code;
  192.     code = ssetfilename(s, op[-1].value.const_bytes, r_size(op - 1));
  193.     if (code < 0) {
  194.     sclose(s);
  195.     return_error(e_VMerror);
  196.     }
  197.     make_stream_file(op - 1, s, file_access);
  198.     pop(1);
  199.     return code;
  200. }
  201.  
  202. /* ------ Level 2 extensions ------ */
  203.  
  204. /* <string> deletefile - */
  205. private int
  206. zdeletefile(i_ctx_t *i_ctx_p)
  207. {
  208.     os_ptr op = osp;
  209.     gs_parsed_file_name_t pname;
  210.     int code = parse_real_file_name(op, &pname, imemory, "deletefile");
  211.  
  212.     if (code < 0)
  213.     return code;
  214.     code = (*pname.iodev->procs.delete_file)(pname.iodev, pname.fname);
  215.     gs_free_file_name(&pname, "deletefile");
  216.     if (code < 0)
  217.     return code;
  218.     pop(1);
  219.     return 0;
  220. }
  221.  
  222. /* <template> <proc> <scratch> filenameforall - */
  223. /****** NOT CONVERTED FOR IODEVICES YET ******/
  224. private int file_continue(P1(i_ctx_t *));
  225. private int file_cleanup(P1(i_ctx_t *));
  226. private int
  227. zfilenameforall(i_ctx_t *i_ctx_p)
  228. {
  229.     os_ptr op = osp;
  230.     file_enum *pfen;
  231.     int code;
  232.  
  233.     check_write_type(*op, t_string);
  234.     check_proc(op[-1]);
  235.     check_read_type(op[-2], t_string);
  236.     /* Push a mark, the pattern, the scratch string, the enumerator, */
  237.     /* and the procedure, and invoke the continuation. */
  238.     check_estack(7);
  239.     pfen = gp_enumerate_files_init((char *)op[-2].value.bytes, r_size(op - 2), imemory);
  240.     if (pfen == 0)
  241.     return_error(e_VMerror);
  242.     push_mark_estack(es_for, file_cleanup);
  243.     *++esp = op[-2];
  244.     *++esp = *op;
  245.     ++esp;
  246.     make_istruct(esp, 0, pfen);
  247.     *++esp = op[-1];
  248.     pop(3);
  249.     code = file_continue(i_ctx_p);
  250.     return (code == o_pop_estack ? o_push_estack : code);
  251. }
  252. /* Continuation operator for enumerating files */
  253. private int
  254. file_continue(i_ctx_t *i_ctx_p)
  255. {
  256.     os_ptr op = osp;
  257.     es_ptr pscratch = esp - 2;
  258.     file_enum *pfen = r_ptr(esp - 1, file_enum);
  259.     uint len = r_size(pscratch);
  260.     uint code =
  261.     gp_enumerate_files_next(pfen, (char *)pscratch->value.bytes, len);
  262.  
  263.     if (code == ~(uint) 0) {    /* all done */
  264.     esp -= 4;        /* pop proc, pfen, scratch, mark */
  265.     return o_pop_estack;
  266.     } else if (code > len)    /* overran string */
  267.     return_error(e_rangecheck);
  268.     else {
  269.     push(1);
  270.     ref_assign(op, pscratch);
  271.     r_set_size(op, code);
  272.     push_op_estack(file_continue);    /* come again */
  273.     *++esp = pscratch[2];    /* proc */
  274.     return o_push_estack;
  275.     }
  276. }
  277. /* Cleanup procedure for enumerating files */
  278. private int
  279. file_cleanup(i_ctx_t *i_ctx_p)
  280. {
  281.     gp_enumerate_files_close(r_ptr(esp + 4, file_enum));
  282.     return 0;
  283. }
  284.  
  285. /* <string1> <string2> renamefile - */
  286. private int
  287. zrenamefile(i_ctx_t *i_ctx_p)
  288. {
  289.     os_ptr op = osp;
  290.     gs_parsed_file_name_t pname1, pname2;
  291.     int code = parse_real_file_name(op - 1, &pname1, imemory,
  292.                     "renamefile(from)");
  293.  
  294.     if (code < 0)
  295.     return code;
  296.     pname2.fname = 0;
  297.     code = parse_real_file_name(op, &pname2, imemory, "renamefile(to)");
  298.     if (code < 0 || pname1.iodev != pname2.iodev ||
  299.     (code = (*pname1.iodev->procs.rename_file)(pname1.iodev,
  300.                         pname1.fname, pname2.fname)) < 0
  301.     ) {
  302.     if (code >= 0)
  303.         code = gs_note_error(e_invalidfileaccess);
  304.     }
  305.     gs_free_file_name(&pname2, "renamefile(to)");
  306.     gs_free_file_name(&pname1, "renamefile(from)");
  307.     if (code < 0)
  308.     return code;
  309.     pop(2);
  310.     return 0;
  311. }
  312.  
  313. /* <file> status <open_bool> */
  314. /* <string> status <pages> <bytes> <ref_time> <creation_time> true */
  315. /* <string> status false */
  316. private int
  317. zstatus(i_ctx_t *i_ctx_p)
  318. {
  319.     os_ptr op = osp;
  320.  
  321.     switch (r_type(op)) {
  322.     case t_file:
  323.         {
  324.         stream *s;
  325.  
  326.         make_bool(op, (file_is_valid(s, op) ? 1 : 0));
  327.         }
  328.         return 0;
  329.     case t_string:
  330.         {
  331.         gs_parsed_file_name_t pname;
  332.         struct stat fstat;
  333.         int code = parse_file_name(op, &pname);
  334.  
  335.         if (code < 0)
  336.             return code;
  337.         code = gs_terminate_file_name(&pname, imemory, "status");
  338.         if (code < 0)
  339.             return code;
  340.         code = (*pname.iodev->procs.file_status)(pname.iodev,
  341.                                pname.fname, &fstat);
  342.         switch (code) {
  343.             case 0:
  344.             check_ostack(4);
  345.             /*
  346.              * Check to make sure that the file size fits into
  347.              * a PostScript integer.  (On some systems, long is
  348.              * 32 bits, but file sizes are 64 bits.)
  349.              */
  350.             push(4);
  351.             make_int(op - 4, stat_blocks(&fstat));
  352.             make_int(op - 3, fstat.st_size);
  353.             /*
  354.              * We can't check the value simply by using ==,
  355.              * because signed/unsigned == does the wrong thing.
  356.              * Instead, since integer assignment only keeps the
  357.              * bottom bits, we convert the values to double
  358.              * and then test for equality.  This handles all
  359.              * cases of signed/unsigned or width mismatch.
  360.              */
  361.             if ((double)op[-4].value.intval !=
  362.                   (double)stat_blocks(&fstat) ||
  363.                 (double)op[-3].value.intval !=
  364.                   (double)fstat.st_size
  365.                 )
  366.                 return_error(e_limitcheck);
  367.             make_int(op - 2, fstat.st_mtime);
  368.             make_int(op - 1, fstat.st_ctime);
  369.             make_bool(op, 1);
  370.             break;
  371.             case e_undefinedfilename:
  372.             make_bool(op, 0);
  373.             code = 0;
  374.         }
  375.         gs_free_file_name(&pname, "status");
  376.         return code;
  377.         }
  378.     default:
  379.         return_op_typecheck(op);
  380.     }
  381. }
  382.  
  383. /* ------ Non-standard extensions ------ */
  384.  
  385. /* <executable_file> .execfile - */
  386. private int
  387. zexecfile(i_ctx_t *i_ctx_p)
  388. {
  389.     os_ptr op = osp;
  390.  
  391.     check_type_access(*op, t_file, a_executable | a_read | a_execute);
  392.     check_estack(4);        /* cleanup, file, finish, file */
  393.     push_mark_estack(es_other, execfile_cleanup);
  394.     *++esp = *op;
  395.     push_op_estack(execfile_finish);
  396.     return zexec(i_ctx_p);
  397. }
  398. /* Finish normally. */
  399. private int
  400. execfile_finish(i_ctx_t *i_ctx_p)
  401. {
  402.     check_ostack(1);
  403.     esp -= 2;
  404.     execfile_cleanup(i_ctx_p);
  405.     return o_pop_estack;
  406. }
  407. /* Clean up by closing the file. */
  408. private int
  409. execfile_cleanup(i_ctx_t *i_ctx_p)
  410. {
  411.     check_ostack(1);
  412.     *++osp = esp[2];
  413.     return zclosefile(i_ctx_p);
  414. }
  415.  
  416. /* <dir> <name> .filenamedirseparator <string> */
  417. private int
  418. zfilenamedirseparator(i_ctx_t *i_ctx_p)
  419. {
  420.     os_ptr op = osp;
  421.     const char *sepr;
  422.  
  423.     check_read_type(*op, t_string);
  424.     check_read_type(op[-1], t_string);
  425.     sepr =
  426.     gp_file_name_concat_string((const char *)op[-1].value.const_bytes,
  427.                    r_size(op - 1),
  428.                    (const char *)op->value.const_bytes,
  429.                    r_size(op));
  430.     make_const_string(op - 1, avm_foreign | a_readonly,
  431.               strlen(sepr), (const byte *)sepr);
  432.     pop(1);
  433.     return 0;
  434. }
  435.  
  436. /* - .filenamelistseparator <string> */
  437. private int
  438. zfilenamelistseparator(i_ctx_t *i_ctx_p)
  439. {
  440.     os_ptr op = osp;
  441.  
  442.     push(1);
  443.     make_const_string(op, avm_foreign | a_readonly, 1,
  444.               (const byte *)&gp_file_name_list_separator);
  445.     return 0;
  446. }
  447.  
  448. /* <name> .filenamesplit <dir> <base> <extension> */
  449. private int
  450. zfilenamesplit(i_ctx_t *i_ctx_p)
  451. {
  452.     os_ptr op = osp;
  453.  
  454.     check_read_type(*op, t_string);
  455. /****** NOT IMPLEMENTED YET ******/
  456.     return_error(e_undefined);
  457. }
  458.  
  459. /* <string> .libfile <file> true */
  460. /* <string> .libfile <string> false */
  461. private int
  462. zlibfile(i_ctx_t *i_ctx_p)
  463. {
  464.     os_ptr op = osp;
  465.     int code;
  466. #define MAX_CNAME 200
  467.     byte cname[MAX_CNAME];
  468.     uint clen;
  469.     gs_parsed_file_name_t pname;
  470.     stream *s;
  471.  
  472.     check_ostack(2);
  473.     code = parse_file_name(op, &pname);
  474.     if (code < 0)
  475.     return code;
  476.     if (pname.iodev == NULL)
  477.     pname.iodev = iodev_default;
  478.     if (pname.iodev != iodev_default) {        /* Non-OS devices don't have search paths (yet). */
  479.     code = zopen_file(&pname, "r", &s, imemory);
  480.     if (code >= 0) {
  481.         code = ssetfilename(s, op->value.const_bytes, r_size(op));
  482.         if (code < 0) {
  483.         sclose(s);
  484.         return_error(e_VMerror);
  485.         }
  486.     }
  487.     if (code < 0) {
  488.         push(1);
  489.         make_false(op);
  490.         return 0;
  491.     }
  492.     make_stream_file(op, s, "r");
  493.     } else {
  494.     ref fref;
  495.  
  496.     code = lib_file_open(pname.fname, pname.len, cname, MAX_CNAME,
  497.                  &clen, &fref, imemory);
  498.     if (code >= 0) {
  499.         s = fptr(&fref);
  500.         code = ssetfilename(s, cname, clen);
  501.         if (code < 0) {
  502.         sclose(s);
  503.         return_error(e_VMerror);
  504.         }
  505.     }
  506.     if (code < 0) {
  507.         if (code == e_VMerror)
  508.         return code;
  509.         push(1);
  510.         make_false(op);
  511.         return 0;
  512.     }
  513.     ref_assign(op, &fref);
  514.     }
  515.     push(1);
  516.     make_true(op);
  517.     return 0;
  518. }
  519.  
  520. /* ------ Initialization procedure ------ */
  521.  
  522. const op_def zfile_op_defs[] =
  523. {
  524.     {"1deletefile", zdeletefile},
  525.     {"1.execfile", zexecfile},
  526.     {"2file", zfile},
  527.     {"3filenameforall", zfilenameforall},
  528.     {"2.filenamedirseparator", zfilenamedirseparator},
  529.     {"0.filenamelistseparator", zfilenamelistseparator},
  530.     {"1.filenamesplit", zfilenamesplit},
  531.     {"1.libfile", zlibfile},
  532.     {"2renamefile", zrenamefile},
  533.     {"1status", zstatus},
  534.         /* Internal operators */
  535.     {"0%file_continue", file_continue},
  536.     {"0%execfile_finish", execfile_finish},
  537.     op_def_end(zfile_init)
  538. };
  539.  
  540. /* ------ File name parsing ------ */
  541.  
  542. /* Parse a file name into device and individual name. */
  543. /* See gsfname.c for details. */
  544. private int
  545. parse_file_name(const ref * op, gs_parsed_file_name_t * pfn)
  546. {
  547.     check_read_type(*op, t_string);
  548.     return gs_parse_file_name(pfn, (const char *)op->value.const_bytes,
  549.                   r_size(op));
  550. }
  551.  
  552. /* Parse a real (non-device) file name and convert to a C string. */
  553. /* See gsfname.c for details. */
  554. private int
  555. parse_real_file_name(const ref *op, gs_parsed_file_name_t *pfn,
  556.              gs_memory_t *mem, client_name_t cname)
  557. {
  558.     check_read_type(*op, t_string);
  559.     return gs_parse_real_file_name(pfn, (const char *)op->value.const_bytes,
  560.                    r_size(op), mem, cname);
  561. }
  562.  
  563. /* ------ Stream opening ------ */
  564.  
  565. /*
  566.  * Open a file specified by a parsed file name (which may be only a
  567.  * device).
  568.  */
  569. private int
  570. zopen_file(const gs_parsed_file_name_t *pfn, const char *file_access,
  571.        stream **ps, gs_memory_t *mem)
  572. {
  573.     gx_io_device *const iodev = pfn->iodev;
  574.  
  575.     if (pfn->fname == NULL)    /* just a device */
  576.     return iodev->procs.open_device(iodev, file_access, ps, mem);
  577.     else {            /* file */
  578.     iodev_proc_open_file((*open_file)) = iodev->procs.open_file;
  579.  
  580.     if (open_file == 0)
  581.         open_file = iodev_os_open_file;
  582.     return open_file(iodev, pfn->fname, pfn->len, file_access, ps, mem);
  583.     }
  584. }
  585.  
  586. /*
  587.  * Define the file_open procedure for the %os% IODevice (also used, as the
  588.  * default, for %pipe% and possibly others).
  589.  */
  590. private int
  591. iodev_os_open_file(gx_io_device * iodev, const char *fname, uint len,
  592.            const char *file_access, stream ** ps, gs_memory_t * mem)
  593. {
  594.     return file_open_stream(fname, len, file_access,
  595.                 file_default_buffer_size, ps,
  596.                 iodev->procs.fopen, mem);
  597. }
  598.  
  599. /* Make a t_file reference to a stream. */
  600. void
  601. make_stream_file(ref * pfile, stream * s, const char *access)
  602. {
  603.     uint attrs =
  604.     (access[1] == '+' ? a_write + a_read + a_execute : 0) |
  605.     imemory_space((gs_ref_memory_t *) s->memory);
  606.  
  607.     if (access[0] == 'r') {
  608.     make_file(pfile, attrs | (a_read | a_execute), s->read_id, s);
  609.     s->write_id = 0;
  610.     } else {
  611.     make_file(pfile, attrs | a_write, s->write_id, s);
  612.     s->read_id = 0;
  613.     }
  614. }
  615.  
  616. /* Open an OS-level file (like fopen), using the search paths if necessary. */
  617. /* Note that it does not automatically look in the current */
  618. /* directory first (or at all): this is like Unix, and unlike MS-DOS. */
  619. private int
  620. lib_file_fopen(gx_io_device * iodev, const char *bname,
  621.            const char *ignore_access, FILE ** pfile,
  622.            char *rfname, uint rnamelen)
  623. {
  624.     char fmode[3];        /* r, [b], null */
  625.     int len = strlen(bname);
  626.     const gs_file_path *pfpath = &gs_lib_path;
  627.     uint pi;
  628.  
  629.     strcpy(fmode, "r");
  630.     strcat(fmode, gp_fmode_binary_suffix);
  631.     if (gp_file_name_is_absolute(bname, len))
  632.     return (*iodev->procs.fopen)(iodev, bname, fmode, pfile,
  633.                      rfname, rnamelen);
  634.     /* Go through the list of search paths */
  635.     for (pi = 0; pi < r_size(&pfpath->list); ++pi) {
  636.     const ref *prdir = pfpath->list.value.refs + pi;
  637.     const char *pstr = (const char *)prdir->value.const_bytes;
  638.     uint plen = r_size(prdir);
  639.     const char *cstr =
  640.     gp_file_name_concat_string(pstr, plen, bname, len);
  641.     int up, i;
  642.     int code;
  643.  
  644.     /* Concatenate the prefix, combiner, and file name. */
  645.     /* Do this carefully in case rfname is the same */
  646.     /* as fname.  (We don't worry about the case */
  647.     /* where rfname only overlaps fname.) */
  648.     up = plen + strlen(cstr);
  649.     if (up + len + 1 > rnamelen)
  650.         return_error(e_limitcheck);
  651.     for (i = len + 1; --i >= 0;)
  652.         rfname[i + up] = bname[i];
  653.     memcpy(rfname, pstr, plen);
  654.     memcpy(rfname + plen, cstr, strlen(cstr));
  655.     code = (*iodev->procs.fopen)(iodev, rfname, fmode,
  656.                      pfile, rfname, rnamelen);
  657.     if (code >= 0)
  658.         return code;
  659.     /* strcpy isn't guaranteed to work for overlapping */
  660.     /* source and destination, so: */
  661.     if (rfname == bname)
  662.         for (i = 0; (rfname[i] = rfname[i + up]) != 0; i++);
  663.     }
  664.     return_error(e_undefinedfilename);
  665. }
  666. /* The startup code calls this to open @-files. */
  667. FILE *
  668. lib_fopen(const char *bname)
  669. {
  670.     FILE *file = NULL;
  671.     /* We need a buffer to hold the expanded file name. */
  672.     char buffer[gp_file_name_sizeof];
  673.     /* We can't count on the IODevice table to have been initialized yet. */
  674.     /* Allocate a copy of the default IODevice. */
  675.     gx_io_device iodev_default_copy;
  676.     int code;
  677.  
  678.     iodev_default_copy = *gx_io_device_table[0];
  679.     code = lib_file_fopen(&iodev_default_copy, bname, "r", &file,
  680.               buffer, gp_file_name_sizeof);
  681.     return (code < 0 ? NULL : file);
  682. }
  683.  
  684. /* Open a file stream on an OS file and create a file object, */
  685. /* using the search paths. */
  686. /* The startup code calls this to open the initialization file gs_init.ps. */
  687. int
  688. lib_file_open(const char *fname, uint len, byte * cname, uint max_clen,
  689.           uint * pclen, ref * pfile, gs_memory_t *mem)
  690. {
  691.     stream *s;
  692.     int code = file_open_stream(fname, len, "r", file_default_buffer_size,
  693.                 &s, lib_file_fopen, mem);
  694.     char *bname;
  695.     uint blen;
  696.  
  697.     if (code < 0)
  698.     return code;
  699.     /* Get the name from the stream buffer. */
  700.     bname = (char *)s->cbuf;
  701.     blen = strlen(bname);
  702.     if (blen > max_clen) {
  703.     sclose(s);
  704.     return_error(e_limitcheck);
  705.     }
  706.     memcpy(cname, bname, blen);
  707.     *pclen = blen;
  708.     make_stream_file(pfile, s, "r");
  709.     return 0;
  710. }
  711.  
  712. /* Open a file stream that reads a string. */
  713. /* (This is currently used only by the ccinit feature.) */
  714. /* The string must be allocated in non-garbage-collectable (foreign) space. */
  715. int
  716. file_read_string(const byte *str, uint len, ref *pfile, gs_ref_memory_t *imem)
  717. {
  718.     stream *s = file_alloc_stream((gs_memory_t *)imem, "file_read_string");
  719.  
  720.     if (s == 0)
  721.     return_error(e_VMerror);
  722.     sread_string(s, str, len);
  723.     s->foreign = 1;
  724.     s->write_id = 0;
  725.     make_file(pfile, a_readonly | imemory_space(imem), s->read_id, s);
  726.     s->save_close = s->procs.close;
  727.     s->procs.close = file_close_disable;
  728.     return 0;
  729. }
  730.  
  731. /* Open a file stream, optionally on an OS file. */
  732. /* Return 0 if successful, error code if not. */
  733. /* On a successful return, the C file name is in the stream buffer. */
  734. /* If fname==0, set up the file entry, stream, and buffer, */
  735. /* but don't open an OS file or initialize the stream. */
  736. int
  737. file_open_stream(const char *fname, uint len, const char *file_access,
  738.          uint buffer_size, stream ** ps, iodev_proc_fopen_t fopen_proc,
  739.          gs_memory_t *mem)
  740. {
  741.     byte *buffer;
  742.     register stream *s;
  743.  
  744.     if (buffer_size == 0)
  745.     buffer_size = file_default_buffer_size;
  746.     if (len >= buffer_size)    /* we copy the file name into the buffer */
  747.     return_error(e_limitcheck);
  748.     /* Allocate the stream first, since it persists */
  749.     /* even after the file has been closed. */
  750.     s = file_alloc_stream(mem, "file_open_stream");
  751.     if (s == 0)
  752.     return_error(e_VMerror);
  753.     /* Allocate the buffer. */
  754.     buffer = gs_alloc_bytes(mem, buffer_size, "file_open_stream(buffer)");
  755.     if (buffer == 0)
  756.     return_error(e_VMerror);
  757.     if (fname != 0) {
  758.     /* Copy the name (so we can terminate it with a zero byte.) */
  759.     char *file_name = (char *)buffer;
  760.     char fmode[4];        /* r/w/a, [+], [b], null */
  761.     FILE *file;
  762.     int code;
  763.  
  764.     memcpy(file_name, fname, len);
  765.     file_name[len] = 0;    /* terminate string */
  766.     /* Open the file, always in binary mode. */
  767.     strcpy(fmode, file_access);
  768.     strcat(fmode, gp_fmode_binary_suffix);
  769.     /****** iodev_default IS QUESTIONABLE ******/
  770.     code = (*fopen_proc)(iodev_default, file_name, fmode, &file,
  771.                  (char *)buffer, buffer_size);
  772.     if (code < 0) {
  773.         gs_free_object(mem, buffer, "file_open_stream(buffer)");
  774.         return code;
  775.     }
  776.     /* Set up the stream. */
  777.     switch (fmode[0]) {
  778.         case 'a':
  779.         sappend_file(s, file, buffer, buffer_size);
  780.         break;
  781.         case 'r':
  782.         /* Defeat buffering for terminals. */
  783.         {
  784.             struct stat rstat;
  785.  
  786.             fstat(fileno(file), &rstat);
  787.             sread_file(s, file, buffer,
  788.                    (S_ISCHR(rstat.st_mode) ? 1 : buffer_size));
  789.         }
  790.         break;
  791.         case 'w':
  792.         swrite_file(s, file, buffer, buffer_size);
  793.     }
  794.     if (fmode[1] == '+')
  795.         s->file_modes |= s_mode_read | s_mode_write;
  796.     s->save_close = s->procs.close;
  797.     s->procs.close = file_close_file;
  798.     } else {            /* save the buffer and size */
  799.     s->cbuf = buffer;
  800.     s->bsize = s->cbsize = buffer_size;
  801.     }
  802.     *ps = s;
  803.     return 0;
  804. }
  805.  
  806. /* Report an error by storing it in the stream's error_string. */
  807. int
  808. filter_report_error(stream_state * st, const char *str)
  809. {
  810.     if_debug1('s', "[s]stream error: %s\n", str);
  811.     strncpy(st->error_string, str, STREAM_MAX_ERROR_STRING);
  812.     /* Ensure null termination. */
  813.     st->error_string[STREAM_MAX_ERROR_STRING] = 0;
  814.     return 0;
  815. }
  816.  
  817. /* Open a file stream for a filter. */
  818. int
  819. filter_open(const char *file_access, uint buffer_size, ref * pfile,
  820.         const stream_procs * procs, const stream_template * template,
  821.         const stream_state * st, gs_memory_t *mem)
  822. {
  823.     stream *s;
  824.     uint ssize = gs_struct_type_size(template->stype);
  825.     stream_state *sst = 0;
  826.     int code;
  827.  
  828.     if (template->stype != &st_stream_state) {
  829.     sst = s_alloc_state(mem, template->stype, "filter_open(stream_state)");
  830.     if (sst == 0)
  831.         return_error(e_VMerror);
  832.     }
  833.     code = file_open_stream((char *)0, 0, file_access,
  834.                 buffer_size, &s, (iodev_proc_fopen_t)0, mem);
  835.     if (code < 0) {
  836.     gs_free_object(mem, sst, "filter_open(stream_state)");
  837.     return code;
  838.     }
  839.     s_std_init(s, s->cbuf, s->bsize, procs,
  840.            (*file_access == 'r' ? s_mode_read : s_mode_write));
  841.     s->procs.process = template->process;
  842.     s->save_close = s->procs.close;
  843.     s->procs.close = file_close_file;
  844.     if (sst == 0) {
  845.     /* This stream doesn't have any state of its own. */
  846.     /* Hack: use the stream itself as the state. */
  847.     sst = (stream_state *) s;
  848.     } else if (st != 0)        /* might not have client parameters */
  849.     memcpy(sst, st, ssize);
  850.     s->state = sst;
  851.     s_init_state(sst, template, mem);
  852.     sst->report_error = filter_report_error;
  853.  
  854.     if (template->init != 0) {
  855.     code = (*template->init)(sst);
  856.     if (code < 0) {
  857.         gs_free_object(mem, sst, "filter_open(stream_state)");
  858.         gs_free_object(mem, s->cbuf, "filter_open(buffer)");
  859.         return code;
  860.     }
  861.     }
  862.     make_stream_file(pfile, s, file_access);
  863.     return 0;
  864. }
  865.  
  866. /* Allocate and return a file stream. */
  867. /* Return 0 if the allocation failed. */
  868. /* The stream is initialized to an invalid state, so the caller need not */
  869. /* worry about cleaning up if a later step in opening the stream fails. */
  870. stream *
  871. file_alloc_stream(gs_memory_t * mem, client_name_t cname)
  872. {
  873.     stream *s;
  874.     gs_ref_memory_t *imem = 0;
  875.  
  876.     /*
  877.      * HACK: Figure out whether this is a gs_ref_memory_t.
  878.      * Avoiding this hack would require rippling a change
  879.      * from gs_memory_t to gs_ref_memory_t into the open_file and
  880.      * open_device procedures of gx_io_device, which in turn would
  881.      * impact other things we don't want to change.
  882.      */
  883.     if (mem->procs.free_object == gs_ref_memory_procs.free_object)
  884.     imem = (gs_ref_memory_t *) mem;
  885.  
  886.     if (imem) {
  887.     /* Look first for a free stream allocated at this level. */
  888.     s = imem->streams;
  889.     while (s != 0) {
  890.         if (!s_is_valid(s) && s->read_id != 0 /* i.e. !overflowed */ ) {
  891.         s->is_temp = 0;    /* not a temp stream */
  892.         return s;
  893.         }
  894.         s = s->next;
  895.     }
  896.     }
  897.     s = s_alloc(mem, cname);
  898.     if (s == 0)
  899.     return 0;
  900.     s_init_ids(s);
  901.     s->is_temp = 0;        /* not a temp stream */
  902.     /*
  903.      * Disable the stream now (in case we can't open the file,
  904.      * or a filter init procedure fails) so that `restore' won't
  905.      * crash when it tries to close open files.
  906.      */
  907.     s_disable(s);
  908.     if (imem) {
  909.     /* Add s to the list of files. */
  910.     if (imem->streams != 0)
  911.         imem->streams->prev = s;
  912.     s->next = imem->streams;
  913.     imem->streams = s;
  914.     } else {
  915.     s->next = 0;
  916.     }
  917.     s->prev = 0;
  918.     return s;
  919. }
  920.  
  921. /* ------ Stream closing ------ */
  922.  
  923. /*
  924.  * Finish closing a file stream.  This used to check whether it was
  925.  * currentfile, but we don't have to do this any longer.  This replaces the
  926.  * close procedure for the std* streams, which cannot actually be closed.
  927.  *
  928.  * This is exported for ziodev.c.  */
  929. int
  930. file_close_finish(stream * s)
  931. {
  932.     return 0;
  933. }
  934.  
  935. /*
  936.  * Close a file stream, but don't deallocate the buffer.  This replaces the
  937.  * close procedure for %lineedit and %statementedit.  (This is WRONG: these
  938.  * streams should allocate a new buffer each time they are opened, but that
  939.  * would overstress the allocator right now.)  This is exported for ziodev.c.
  940.  * This also replaces the close procedure for the string-reading stream
  941.  * created for gs_run_string.
  942.  */
  943. int
  944. file_close_disable(stream * s)
  945. {
  946.     int code = (*s->save_close)(s);
  947.  
  948.     if (code)
  949.     return code;
  950.     /* Increment the IDs to prevent further access. */
  951.     s->read_id = s->write_id = (s->read_id | s->write_id) + 1;
  952.     return file_close_finish(s);
  953. }
  954.  
  955. /* Close a file stream.  This replaces the close procedure in the stream */
  956. /* for normal (OS) files and for filters. */
  957. int
  958. file_close_file(stream * s)
  959. {
  960.     stream *stemp = s->strm;
  961.     gs_memory_t *mem;
  962.     int code = file_close_disable(s);
  963.  
  964.     if (code)
  965.     return code;
  966.     /*
  967.      * Check for temporary streams created for filters.
  968.      * There may be more than one in the case of a procedure-based filter,
  969.      * or if we created an intermediate stream to ensure
  970.      * a large enough buffer.  Note that these streams may have been
  971.      * allocated by file_alloc_stream, so we mustn't free them.
  972.      */
  973.     while (stemp != 0 && stemp->is_temp != 0) {
  974.     stream *snext = stemp->strm;
  975.  
  976.     mem = stemp->memory;
  977.     if (stemp->is_temp > 1)
  978.         gs_free_object(mem, stemp->cbuf,
  979.                "file_close(temp stream buffer)");
  980.     s_disable(stemp);
  981.     stemp = snext;
  982.     }
  983.     mem = s->memory;
  984.     gs_free_object(mem, s->cbuf, "file_close(buffer)");
  985.     if (s->close_strm && stemp != 0)
  986.     return sclose(stemp);
  987.     return 0;
  988. }
  989.  
  990. /* Close a file object. */
  991. /* This is exported only for gsmain.c. */
  992. int
  993. file_close(ref * pfile)
  994. {
  995.     stream *s;
  996.  
  997.     if (file_is_valid(s, pfile)) {    /* closing a closed file is a no-op */
  998.     if (sclose(s))
  999.         return_error(e_ioerror);
  1000.     }
  1001.     return 0;
  1002. }
  1003.